﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using H2.NET.Data.Common;
using H2.NET.Business;
using System.Data;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using H2.NET.Web.BI.Model;
using System.Linq;

namespace H2.NET.Web.Controls
{
    public partial class DwzAttachment : TaskControl
    {
        public DataTable xls = new DataTable();
        public bool showXls{get;set;}
        #region 属性 AllowUpload(是否允许上传)
        public bool AllowUpload
        {
            get
            {
                return ViewState["AllowUpload"] == null ? true : (bool)ViewState["AllowUpload"];
            }
            set
            {
                ViewState["AllowUpload"] = value;
            }
        }
        #endregion

        #region 属性 AllowDelete(是否允许删除)
        public bool AllowDelete
        {
            get
            {
                return ViewState["AllowDelete"] == null ? true : (bool)ViewState["AllowDelete"];
            }
            set
            {
                ViewState["AllowDelete"] = value;
            }
        }
        #endregion

        #region 属性 FileClass(文件类别)
        public string FileClass
        {
            get
            {
                return ViewState["FileClass"] == null ? "" : (string)ViewState["FileClass"];
            }
            set
            {
                ViewState["FileClass"] = value;
            }
        }
        #endregion

        #region 属性 Process(文件类别)
        public string PProcess
        {
            get
            {
                return ViewState["PProcess"] == null ? "" : (string)ViewState["PProcess"];
            }
            set
            {
                ViewState["PProcess"] = value;
            }
        }
        #endregion

        #region 属性 Step(文件类别)
        public string PStep
        {
            get
            {
                return ViewState["PStep"] == null ? "" : (string)ViewState["PStep"];
            }
            set
            {
                ViewState["PStep"] = value;
            }
        }
        #endregion

        #region 属性 PIncident(文件类别)
        public int PIncident
        {
            get
            {
                return ViewState["PIncident"] == null ? 0 : (int)ViewState["PIncident"];
            }
            set
            {
                ViewState["PIncident"] = value;
            }
        }
        #endregion

        #region 属性 Max(最大上传数量)
        public int Max
        {
            get
            {
                return ViewState["Max"] == null ? 9999 : (int)ViewState["Max"];
            }
            set
            {
                ViewState["Max"] = value;
            }
        }

        public string IsShow { get { return AllowUpload && this.rep_Attachment.Items.Count < Max ? "" : "display:none;"; } }

        #endregion

        #region 属性 FirstFile(第一个文件)
        public string FirstFilePath
        {
            get
            {
                return ViewState["FirstFilePath"] == null ? "" : (string)ViewState["FirstFilePath"];
            }
            set
            {
                ViewState["FirstFilePath"] = value;
            }
        }
        #endregion

        #region 属性 IsHaveAttachment(是否存在附件)
        public bool IsHaveAttachment
        {
            get
            {
                return ViewState["IsHaveAttachment"] == null ? false : (bool)ViewState["IsHaveAttachment"];
            }
            set
            {
                ViewState["IsHaveAttachment"] = value;
            }
        }
        #endregion

        #region 事件 Load (页面)
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //列表绑定
                Bind();
            }
        }
        #endregion

        #region 事件 ItemCommand (列表)
        protected void rep_Attachment_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Footer)
            {
                //文件上传
                if (e.CommandName == "Upload")
                {
                    RepeaterItem rep = (RepeaterItem)rep_Attachment.Controls[rep_Attachment.Controls.Count - 1];
                    FileUpload fu = (FileUpload)rep.FindControl("File");

                    //如果存在文件的情况
                    if (fu.HasFile)
                    {
                        //文件类型上传限制
                        //string Ext = System.IO.Path.GetExtension(fu.FileName).ToLower();
                        //string[] AllowExt = { ".gif", ".bmp", ".png", ".jpg" };

                        try
                        {
                            //判断目录是否存在
                            string bs = Util.AppSettings("path");
                            string path = Path.Combine(bs, (string.IsNullOrEmpty(PProcess) ? TaskAPI.Process : PProcess));
                            string date = System.DateTime.Now.ToString("yyyyMMddHHmmssfff");

                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
                            
                            //文件保存
                            fu.SaveAs(path + @"\" + date + @"~" + fu.FileName);

                            if (showXls)
                            {
                                xls = readXls(path + @"\" + date + @"~" + fu.FileName);
                                Cache.Insert("xlsData", xls);
                            }
                            //记录集保存
                            H2.NET.Business.t_Attachment att = new H2.NET.Business.t_Attachment();
                            att.ID = date;
                            att.Process = (string.IsNullOrEmpty(PProcess) ? TaskAPI.Process : PProcess);
                            att.Incident = (string.IsNullOrEmpty(PProcess) ? TaskAPI.Incident : PIncident);
                            att.Step = (string.IsNullOrEmpty(PProcess) ? TaskAPI.Step : PStep);
                            att.UserName = UserAPI.UserName;
                            att.UserFullName = UserAPI.UserFullName;
                            att.Department = UserAPI.Department;
                            att.Time = System.DateTime.Now;
                            att.FileName = fu.FileName;
                            att.FileClass = FileClass;
                            att.FilePath = path + @"\" + date + @"~" + fu.FileName;
                            att.Status = 1;
                            Storage.Save(Storage.Context1, att);

                            //列表绑定
                            Bind();
                        }
                        catch (Exception)
                        {
                        }
                    }
                }

                //文件删除
                if (e.CommandName == "Delete")
                {
                    (H2.NET.Business.t_Attachment.id == e.CommandArgument).Edit<H2.NET.Business.t_Attachment>(Storage.Context1, o =>
                    {
                        o.Time = System.DateTime.Now;
                        o.Status = 2;
                    });
                    //列表绑定
                    Bind();
                }

                if (e.CommandName == "View")
                {
                    H2.NET.Business.t_Attachment attachment = (H2.NET.Business.t_Attachment.id == e.CommandArgument).ListFirst<H2.NET.Business.t_Attachment>();
                    if (attachment.FilePath == null || !File.Exists(attachment.FilePath))
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "tip", "alert('对不起，该文件已被删除')", true);
                        return;
                    }
                    //以字符流的形式下载文件
                    FileStream fs = new FileStream(attachment.FilePath, FileMode.Open);
                    byte[] bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    Response.ContentType = "application/octet-stream";
                    //通知浏览器下载文件而不是打开
                    Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(attachment.FileName, System.Text.Encoding.UTF8));
                    Response.BinaryWrite(bytes);
                    Response.Flush();
                    Response.End();



                    //Response.ContentType = "application/x-zip-compressed";
                    //Response.AddHeader("Content-Disposition", "attachment;filename=z.zip");
                    //string filename = attachment.FilePath;
                    //Response.TransmitFile(filename);
                }
            }
        }
        #endregion

        #region 读取xls内容

        private DataTable readXls(string path)
        {
            IWorkbook hssfworkbook;
            DataTable dt = new DataTable();
            try
            {
                using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    hssfworkbook = WorkbookFactory.Create(file);
                }
                ISheet sheet = hssfworkbook.GetSheetAt(0);
                System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
                //一行最后一个方格的编号 即总的列数  
                for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)
                {
                    string cName = sheet.GetRow(0).Cells[j].ToString();
                    string eName = "";
                    using (var ctx = new UltimusMDC3Entities())
                    {
                        string tbName = sheet.SheetName;
                        var col = ctx.bi_Column.Where(c => c.bi_Table.table_name == tbName && c.name_cn == cName).FirstOrDefault();
                        if(col!=null){
                            eName = col.column_name;
                        }
                        else
                        {
                            return new DataTable();
                        }
                    }
                    dt.Columns.Add(!string.IsNullOrEmpty(eName)?eName:cName);
                }
                while (rows.MoveNext())
                {
                    IRow row = (HSSFRow)rows.Current;
                    DataRow dr = dt.NewRow();

                    for (int i = 0; i < row.LastCellNum; i++)
                    {
                        ICell cell = row.GetCell(i);


                        if (cell == null)
                        {
                            dr[i] = null;
                        }
                        else
                        {
                            dr[i] = cell.ToString();
                        }
                    }
                    dt.Rows.Add(dr);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return dt;
        }

        #endregion

        #region 方法 绑定
        private void Bind()
        {
            Expression exp = new Expression();
            if (string.IsNullOrEmpty(PProcess))
            {
                exp &= H2.NET.Business.t_Attachment.process == TaskAPI.Process;
                exp &= H2.NET.Business.t_Attachment.incident == TaskAPI.Incident;

                if (TaskAPI.Incident <= 0)
                {
                    exp &= H2.NET.Business.t_Attachment.username == UserAPI.UserName;
                }
            }
            else
            {
                exp &= H2.NET.Business.t_Attachment.process == PProcess;
                exp &= H2.NET.Business.t_Attachment.incident == PIncident;
            }

            exp &= H2.NET.Business.t_Attachment.fileClass == FileClass;
            exp &= H2.NET.Business.t_Attachment.status == 1;

            List<H2.NET.Business.t_Attachment> list = (List<H2.NET.Business.t_Attachment>)exp.List<H2.NET.Business.t_Attachment>(Storage.Context1, new Region(0, 100), H2.NET.Business.t_Attachment.time.Asc);

            //加密文件名
            foreach (H2.NET.Business.t_Attachment att in list)
            {
                att.EncryptFileName = Util.Encrypt((string.IsNullOrEmpty(PProcess) ? TaskAPI.Process : PProcess) + @"\" + att.ID + "~" + att.FileName);
            }

            FirstFilePath = list.Count > 0 ? Util.AppSettings("path") + (string.IsNullOrEmpty(PProcess) ? TaskAPI.Process : PProcess) + @"\" + list[0].ID + "~" + list[0].FileName : "";
            IsHaveAttachment = list.Count > 0;

            rep_Attachment.DataSource = list;
            rep_Attachment.DataBind();

            //是否禁用删除
            foreach (RepeaterItem rep in rep_Attachment.Items)
            {
                string UserName = ((Label)rep.FindControl("lbl_UserName")).Text.ToString();
                if (AllowDelete && UserName.ToLower() == UserAPI.UserName.ToLower())
                {
                    ((ImageButton)rep.FindControl("img_Del")).Visible = true;
                }
                else
                {
                    ((ImageButton)rep.FindControl("img_Del")).Visible = false;
                }
            }

            //注册 文件下载 Javascript 事件
            foreach (RepeaterItem ri in rep_Attachment.Items)
            {
                ImageButton ib = (ImageButton)ri.Controls[5];
                //ib.Attributes["onclick"] = "FileHandler('" + ResolveUrl("~/FileHandler.ashx") + "?File=" + ib.CommandArgument + "');";
            }
        }
        #endregion
    }
}